﻿using DevExpress.Web.ASPxUploadControl;
using RR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    const string UploadDirectory = "/dogovor/";
    private RegistRar regrar = new RegistRar();
    string filePath = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void RefreshGrid()
    {
        //string kontr = cbb_kontr.Value.ToString();
        //ds_dog.WhereParameters.Clear();
        //ds_dog.AutoGenerateWhereClause = true;
        //ds_dog.WhereParameters.Add("KONTRAGENT", System.Data.DbType.Int32, kontr);
    }

    protected void UploadBtn_Click(object sender, EventArgs e)
    {
        //if (FileUpload1.HasFile)
        //{
        //    string resFileName = MapPath(UploadDirectory) + FileUpload1.FileName;
        //    FileUpload1.SaveAs(resFileName);
        //    Label1.Text = FileUpload1.FileName;


        //ASPxUploadControl1.UploadedFiles.SaveAs(resFileName);
        // }
    }
    protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
    {
        //for (int i = 0; i < ASPxUploadControl1.UploadedFiles.Length; i++)
        //{
        //}
        UploadedFile file = ASPxUploadControl1.UploadedFiles[0];
        if (file.FileName != "" && file.IsValid)
        {
            try
            {
                e.CallbackData = "success";
                string fileName = file.FileName;
                string virtPath = UploadDirectory + fileName;
                filePath = Page.MapPath(virtPath);

                string Kontr = grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "KONTRAGENT").ToString();

                file.SaveAs(filePath);
                Session["FPath"] = virtPath;
                Session["FFile"] = fileName;
                ASPxUploadControl1.ClientVisible = false;
                //если имеется старый загруженный файл к договору, то удаляем его
                if (Session["FFilePrev"] != null) { DeleteDog(Session["FFilePrev"].ToString()); }
            }
            catch (System.IO.IOException ex)
            {
                e.ErrorText = ex.Message;
                e.CallbackData = "error";
                Session["FPath"] = null;
                Session["FFile"] = null;
            }
        }
        //string fileName = e.UploadedFile.FileName;
        //string virtPath = UploadDirectory + fileName;
        //filePath = Page.MapPath(virtPath);
        //e.UploadedFile.SaveAs(filePath);
        //Session["FPath"] = virtPath;
        //ASPxUploadControl1.ClientVisible = false;
        //e.CallbackData = virtPath;
    }

    protected void grd_Dog_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("DOG_gen");

        //if (e.NewValues["DATAPATH"] == null)
        //    e.NewValues["DATAPATH"] = Session["FPath"];
        //if (e.NewValues["FILENAME"] == null)
        //    e.NewValues["FILENAME"] = Session["FFile"];

    }
    protected void grd_Dog_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
    {
        Session["FPath"] = null;
        Session["FFile"] = null;
    }
    protected void grd_Dog_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
    {

    }
    protected void grd_Dog_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
    {
        //if (e.DataColumn.FieldName == "DATAPATH" && e.GetValue("DATAPATH") != null && e.GetValue("DATAPATH")!="")
        //{
        //    e.Cell.Text = String.Format("<a href='{0}>Выяснить вес нестандартного груза (камень)</a>", e.GetValue("DATAPATH"));
        //}
    }
    protected void grd_Dog_CustomColumnDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDisplayTextEventArgs e)
    {
        if (e.Column.FieldName == "DATAPATH" && e.Value != "" && e.Value != null)
        {
            // e.DisplayText = String.Format("<a href='{0}'>скачать</a>", Convert.ToString(e.Value));
        }
    }
    protected void grd_Dog_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        //удалем предыдущий загруженный файл
        //if (e.OldValues["FILENAME"] != null && e.OldValues["FILENAME"] != "")
        //{
        //    filePath = Page.MapPath(e.OldValues["DATAPATH"].ToString());
        //    Session["FFilePrev"] = filePath;
        //}

        if (Session["FPath"] != null)
        {
            if (e.NewValues["DATAPATH"] == null)
                e.NewValues["DATAPATH"] = Session["FPath"];
            if (e.NewValues["FILENAME"] == null)
                e.NewValues["FILENAME"] = Session["FFile"];
        }
    }
    protected void grd_Dog_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatedEventArgs e)
    {
        Session["FPath"] = null;
        Session["FFile"] = null;
    }
    protected void menu_exp_ItemClick(object source, DevExpress.Web.ASPxMenu.MenuItemEventArgs e)
    {
        if (e.Item.Name == "btn_Excel")
            grd_export.WriteXlsxToResponse();
    }

    protected void grd_Dog_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
    {

    }

    protected void DeleteDog(string fPath)
    {
        try
        {
            filePath = Page.MapPath(fPath);
            File.Delete(filePath);
            Session["FFilePrev"] = null;
        }
        catch (Exception)
        {

            throw;
        }
    }

    protected void DeleteDir(string dir)
    {
        if (Directory.Exists(dir))
        {
            //удаляем все файлы в директории
            DirectoryInfo di = new DirectoryInfo(dir);
            foreach (FileInfo fi in di.GetFiles())
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        else
        {
            Directory.CreateDirectory(dir);
        }
    }

    protected void Upload_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
        UploadedFile file = Upload.UploadedFiles[0];
        if (file.FileName != "" && file.IsValid)
        {
            try
            {
                e.CallbackData = "success";


                string fileName = file.FileName;
                string virtPath = String.Format("{0}{1}", Session["FSavePath"], fileName);
                filePath = Page.MapPath(virtPath);
                string dir = Page.MapPath(Session["FSavePath"].ToString());
                DeleteDir(dir);

                file.SaveAs(filePath);
                Session["FPath"] = virtPath;
                Session["FFile"] = fileName;
                Upload.ClientVisible = false;
                //если имеется старый загруженный файл к договору, то удаляем его
                if (Session["FFilePrev"] != null) { DeleteDog(Session["FFilePrev"].ToString()); }
                int code = Convert.ToInt32(Session["FDogCode"]);
                //записываем изменения в базу
                UpdatePath(virtPath, fileName, code);
                //Response.Redirect("~/Arh/dog.aspx",false);
            }
            catch (System.IO.IOException ex)
            {
                e.ErrorText = ex.Message;
                e.CallbackData = "error";
                Session["FPath"] = null;
                Session["FFile"] = null;
            }
        }
    }

    protected void UpdatePath(string path, string filename, int code)
    {
        var query = (from d in regrar.DOG
                     where d.CODE == code
                     select d).First();
        query.DATAPATH = path;
        query.FILENAME = filename;
        regrar.SaveChanges();
        grd_Dog.DataBind();
        //обнуляем сессию
        Session["FDogCode"] = null;
        
    }

    protected void cbPanel_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        string fileName = string.Empty;
        switch (e.Parameter)
        {
            case "select":
                int CODE = Convert.ToInt32(grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "CODE"));
                string Kontr = grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "KONTRAGENT").ToString();
                string dogNum = grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "NOMDOG").ToString();
                //путь к каталогу загрузки файла
                Session["FSavePath"] = String.Format("{0}{1}/{2}/", UploadDirectory, Kontr, dogNum);
                Session["FDogCode"] = CODE;
                if (grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "FILENAME") != null)
                {
                    fileName = grd_Dog.GetRowValues(grd_Dog.FocusedRowIndex, "FILENAME").ToString();
                    //путь к уже загруженному файлу договора
                    Session["FFilePrev"] = String.Format("{0}{1}/{2}/{3}", UploadDirectory, Kontr, dogNum, fileName);
                }
                else
                {
                    Session["FFilePrev"] = null;
                }

                break;
        }
    }


    protected void grd_Dog_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletedEventArgs e)
    {
        string path = Session["FSavePath"].ToString();
        if (path != "" && path != null)
            DeleteDir(Page.MapPath(path));
    }
}